package com.thinkinjava.typeinformation;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description 动态代理
 * @Author
 * @Date 2019/10/5 21:55
 **/
class DynamicProxyHandler implements InvocationHandler {
    private Object proxied;

    public DynamicProxyHandler(Object proxied) {
        this.proxied = proxied;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //在这里做需要加的逻辑 proxy慎用 proxy表示代理对象
        System.out.println("方法名：" + method.getName() + "参数：" + args);
        return method.invoke(proxied,args);
    }
}

class SimpleDynamicProxy{
    public static void consumer(Interface iface){
        iface.doSomething();
        iface.someThingElse("BBBB");
    }

    public static void main(String[] args) {
        RealObject realObject = new RealObject();

        consumer(realObject);

        //使用动态代理
        Interface anInterface = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[]{Interface.class}, new DynamicProxyHandler(realObject));
        consumer(anInterface);
    }
}
